//
//  MewsTableViewController.m
//  ZeroCorner
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 Zero_Zhou. All rights reserved.
//

#import "MewsTableViewController.h"
#import "MJRefresh.h"
#import "MJExtension.h"
#import "ZZNetworkTools.h"
#import "UIImageView+WebCache.h"
#import "ZZNewsModel.h"
#import "NewsCell.h"
#import "ZZdetailViewController.h"
#import "ZZPhotosViewController.h"

@interface MewsTableViewController ()
//数据数组
@property (nonatomic,strong) NSMutableArray *arrayList;
@property (nonatomic,assign) BOOL updata;
@end

@implementation MewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(welcome) name:@"ZZAdvertisementKey" object:nil];
    
    self.view.backgroundColor = [UIColor clearColor];
    [self.tableView addHeaderWithTarget:self action:@selector(loadData)];
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreData)];
    self.updata = YES;
    
    [self.tableView headerBeginRefreshing];
}
-(BOOL)prefersStatusBarHidden{
    return YES;
}

-(void)setUrlString:(NSString *)urlString{
    _urlString = urlString;
    
}
-(void)welcome{
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"update"];
    [self.tableView headerBeginRefreshing];
}

-(void)viewWillAppear:(BOOL)animated{
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"updata"]) {
        return;
    }
    if (self.updata == YES) {
        [self.tableView headerBeginRefreshing];
        self.updata = NO;
    }
    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"contentStart" object:nil]];
}

//下拉刷新
-(void)loadData{
    // http://c.m.163.com//nc/article/headline/T1348647853363/0-30.html
    NSString *allUrlstring = [NSString stringWithFormat:@"/nc/article/%@/0-20.html",self.urlString];
    [self loadDataForType:1 withURL:allUrlstring];
}
//上拉加载
-(void)loadMoreData{
    NSString *allUrlstring = [NSString stringWithFormat:@"/nc/article/%@/%ld-20.html",self.urlString,(self.arrayList.count - self.arrayList.count%10)];
    [self loadDataForType:2 withURL:allUrlstring];
}
//公共方法
- (void)loadDataForType:(int)type withURL:(NSString *)allUrlstring{
    [[[ZZNetworkTools sharedNetworkTools]GET:allUrlstring parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *key = [[responseObject keyEnumerator] nextObject];
        
        NSArray *temArray = responseObject[key];
        NSMutableArray *arrayM = [ZZNewsModel objectArrayWithKeyValuesArray:temArray];
        
        if (type == 1) {
            self.arrayList = arrayM;
            [self.tableView headerEndRefreshing];
            [self.tableView reloadData];
        }else if (type == 2){
            [self.arrayList addObjectsFromArray:arrayM];
            [self.tableView footerEndRefreshing];
            [self.tableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }] resume];
}    //可以用封装实现
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.arrayList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZNewsModel *newsModel = [[ZZNewsModel alloc]init];
    newsModel = self.arrayList[indexPath.row];
    NSString *ID = [NewsCell idForRow:newsModel];
    if ((indexPath.row%20 == 0)&&(indexPath.row != 0)) {
        ID = @"NewsCell";
    }
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    cell.NewsModel = newsModel;
    
    
    // Configure the cell...
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZNewsModel *newsModel = self.arrayList[indexPath.row];
    CGFloat rowHeight = [NewsCell heightForRow:newsModel];
    if ((indexPath.row%20 == 0)&&(indexPath.row != 0)) {
        rowHeight = 80;
    }
    return rowHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //刚选中又马上取消，格子不变色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = [UIColor yellowColor];
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:[ZZdetailViewController class]]) {
        
        NSInteger x = self.tableView.indexPathForSelectedRow.row;
        ZZdetailViewController *dc = segue.destinationViewController;
        ZZNewsModel *newsModel = [[ZZNewsModel alloc]init];
        newsModel = self.arrayList[x];
        dc.newsModel = newsModel;
        NSLog(@"#####%@",dc.newsModel);
        dc.index = self.index;
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
    }else{
        NSInteger x = self.tableView.indexPathForSelectedRow.row;
        ZZdetailViewController *pc = segue.destinationViewController;
        pc.newsModel = self.arrayList[x];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
